const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { logOperation } = require('./logs');

// 状态码定义
const CODE = {
  SUCCESS: 0,
  PARAM_ERROR: 1001,
  NOT_FOUND: 1002,
  SERVER_ERROR: 500,
  NO_PERMISSION: 1003
};

/**
 * 获取项目列表
 * GET /api/projects
 * 支持分页、搜索和状态筛选
 */
router.get('/lists', async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      name,
      status,
      startDate,
      endDate,
      leaderId
    } = req.query;

    let conditions = [];
    let params = [];
    let whereClause = '';

    // 构建查询条件
    if (name) {
      conditions.push('p.name LIKE ?');
      params.push(`%${name}%`);
    }
    if (status) {
      conditions.push('p.status = ?');
      params.push(status);
    }
    if (startDate && endDate) {
      conditions.push('p.start_date BETWEEN ? AND ?');
      params.push(startDate, endDate);
    }
    if (leaderId) {
      conditions.push('p.leader_id = ?');
      params.push(leaderId);
    }

    if (conditions.length > 0) {
      whereClause = 'WHERE ' + conditions.join(' AND ');
    }

    // 计算总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM projects p ${whereClause}`,
      params
    );
    const total = countResult[0].total;

    // 获取分页数据
    const offset = (page - 1) * pageSize;
    const [projects] = await pool.execute(
      `SELECT p.*, u.username as leader_name, u.real_name as leader_real_name,
        (SELECT COUNT(*) FROM modules WHERE project_id = p.id) as module_count,
        (SELECT COUNT(*) FROM bugs WHERE project_id = p.id) as bug_count
       FROM projects p
       LEFT JOIN users u ON p.leader_id = u.id
       ${whereClause}
       ORDER BY p.start_date DESC
       LIMIT ? OFFSET ?`,
      [...params, parseInt(pageSize), offset]
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取项目列表成功',
      data: {
        total,
        list: projects,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    console.error('获取项目列表错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 创建新项目
 * POST /api/projects
 */
router.post('/add', async (req, res) => {
  const {userId} = req.user; //用户id
  console.log("token中的用户信息:",userId)
  try {
    // 处理 x-www-form-urlencoded 格式
    const {
      name = req.body['name'],
      description = req.body['description'],
      startDate = req.body['startDate'] || req.body['start_date'],
      endDate = req.body['endDate'] || req.body['end_date'],
      status = req.body['status'] || 'pending',
      leaderId = req.body['leaderId'] || req.body['leader_id'],
      budget = req.body['budget'] || 0.00,
      priority = req.body['priority'] || '中'
    } = req.body;

    // 参数验证
    if (!name) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '项目名称不能为空'
      });
    }

    // 检查项目是否已存在
    const [existingProjects] = await pool.execute(
      'SELECT * FROM projects WHERE name = ?',
      [name]
    );

    if (existingProjects.length > 0) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '项目名称已存在'
      });
    }

    // 项目预算长长度验证
    if (budget.toString().length > 10) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '项目预算不能超过10位'
      });
    }

    // 检查项目负责人是否存在
    const [existingUsers] = await pool.execute(
      'SELECT * FROM users WHERE id = ?',
      [leaderId]
    );

    if (existingUsers.length === 0) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '项目负责人不存在'
      });
    } 

    // 插入新项目
    const [result] = await pool.execute(
      'INSERT INTO projects (name, description, start_date, end_date, status, leader_id, budget, priority) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [name, description, startDate, endDate, status, leaderId, budget, priority]
    );

    console.log(req.user, 'create', '项目管理', `创建新项目：${name}`, req.ip, req.headers['user-agent']);
    // user是从token中解析出来的，怎么取


    // 记录操作日志
    await logOperation(
      {
        userId: userId,
        type: 'create',
        module: '项目管理',
        details: `创建新项目：${name}`,
        ip: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '项目创建成功',
      data: {
        id: result.insertId,
        name,
        description,
        startDate,
        endDate,
        status,
        leaderId,
        budget,
        priority
      }
    });
  } catch (error) {
    console.error('创建项目错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取项目详情
 * GET /api/projects/:id
 */
router.get('/details/:id', async (req, res) => {
  try {
    const { id } = req.params;

    // 获取项目基本信息
    const [projects] = await pool.execute(
      `SELECT p.*, u.username as leader_name, u.real_name as leader_real_name
       FROM projects p
       LEFT JOIN users u ON p.leader_id = u.id
       WHERE p.id = ?`,
      [id]
    );

    if (projects.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '项目不存在'
      });
    }

    const project = projects[0];

    // 获取项目成员
    const [members] = await pool.execute(
      `SELECT 
         pm.user_id,
         pm.role,
         u.username,
         u.real_name,
         u.email,
         pm.join_date
       FROM project_members pm
       LEFT JOIN users u ON pm.user_id = u.id
       WHERE pm.project_id = ?`,
      [id]
    );

    // 获取项目模块
    const [modules] = await pool.execute(
      `SELECT 
         m.*,
         u.username as leader_name,
         (SELECT COUNT(*) FROM bugs WHERE module_id = m.id AND status != 'closed') as active_bug_count
       FROM modules m
       LEFT JOIN users u ON m.leader_id = u.id
       WHERE m.project_id = ?`,
      [id]
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取项目详情成功',
      data: {
        ...project,
        members,
        modules
      }
    });
  } catch (error) {
    console.error('获取项目详情错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 更新项目
 * PUT /api/projects/:id
 */
router.put('/save/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      name = req.body['name'],
      description = req.body['description'],
      startDate = req.body['startDate'] || req.body['start_date'],
      endDate = req.body['endDate'] || req.body['end_date'],
      status = req.body['status'],
      leaderId = req.body['leaderId'] || req.body['leader_id'],
      budget = req.body['budget'],
      priority = req.body['priority']
    } = req.body;

    // 参数验证
    if (!name) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '项目名称不能为空'
      });
    }

    // 更新项目
    const [result] = await pool.execute(
      'UPDATE projects SET name = ?, description = ?, start_date = ?, end_date = ?, status = ?, leader_id = ?, budget = ?, priority = ? WHERE id = ?',
      [name, description, startDate, endDate, status, leaderId, budget, priority, id]
    );

    if (result.affectedRows === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '项目不存在'
      });
    }

    // 记录操作日志
    await logOperation(
      {
        userId: req.user.userId,
        type: 'update',
        module: '项目管理',
        details: `更新项目：${id}`,
        ip: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '项目更新成功',
      data: {
        id,
        name,
        description,
        startDate,
        endDate,
        status,
        leaderId,
        budget,
        priority
      }
    });
  } catch (error) {
    console.error('更新项目错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 删除项目
 * DELETE /api/projects/:id
 */
router.delete('/delete/:id', async (req, res) => {
  try {
    const { id } = req.params;

    // 检查项目是否存在
    const [project] = await pool.execute(
      'SELECT name FROM projects WHERE id = ?',
      [id]
    );
    if (project.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '项目不存在'
      });
    }

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 删除项目相关的所有数据
      await connection.execute('DELETE FROM bug_comments WHERE bug_id IN (SELECT id FROM bugs WHERE project_id = ?)', [id]);
      await connection.execute('DELETE FROM bugs WHERE project_id = ?', [id]);
      await connection.execute('DELETE FROM modules WHERE project_id = ?', [id]);
      await connection.execute('DELETE FROM project_members WHERE project_id = ?', [id]);
      await connection.execute('DELETE FROM projects WHERE id = ?', [id]);

      await connection.commit();

      // 记录操作日志
      await logOperation(
        {
          userId: req.user.userId,
          type: 'delete',
          module: '项目管理',
          details: `删除项目：${project[0].name}`,
          ip: req.ip,
          userAgent: req.headers['user-agent']
        }
      );

      res.json({
        code: CODE.SUCCESS,
        message: '删除项目成功'
      });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('删除项目错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取项目统计信息
 * GET /api/projects/statistics/overview
 */
router.get('/statistics/overview', async (req, res) => {
  try {
    // 获取项目状态统计
    const [statusStats] = await pool.execute(
      `SELECT status, COUNT(*) as count
       FROM projects
       GROUP BY status`
    );

    // 获取进行中的项目数量
    const [activeProjects] = await pool.execute(
      `SELECT COUNT(*) as count
       FROM projects
       WHERE status = '进行中'`
    );

    // 获取即将到期的项目
    const [upcomingDeadlines] = await pool.execute(
      `SELECT id, name, end_date
       FROM projects
       WHERE status = '进行中'
       AND end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
       ORDER BY end_date ASC`
    );

    // 获取最近创建的项目
    const [recentProjects] = await pool.execute(
      `SELECT p.*, u.username as leader_name
       FROM projects p
       LEFT JOIN users u ON p.leader_id = u.id
       ORDER BY p.id DESC
       LIMIT 5`
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取项目统计信息成功',
      data: {
        statusStats,
        activeProjectCount: activeProjects[0].count,
        upcomingDeadlines,
        recentProjects
      }
    });
  } catch (error) {
    console.error('获取项目统计信息错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

module.exports = router;
